package com.qhzz.permissionlib;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;

import com.qhzz.permissionlib.source.Source;

import java.util.ArrayList;
import java.util.List;

public class ProcessRequest implements Request,Rationale,PermissionActivity.PermissionListener{

    private static final String TAG = "AndPermission";

    private String[] mPermissions;
    private Source source;
    private OnGrantListener onGrantListener;
    private String[] mDeniedPermissions;
    // 曾经拒绝过再次申请时的监听  这也时一个默认值
    private PermissionActivity.RationaleListener rationaleListener = new PermissionActivity.RationaleListener() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onRationaleResult(boolean showRationale) {
            if (showRationale && rationaleListener != null) {

                new RationaleDialog(source.getContext(), ProcessRequest.this).show();
            } else {
                resume();
            }
        }
    };
    // 获取权限失败监听   这是一个默认监听
    private OnRefuseListener onRefuseListener = new OnRefuseListener() {
        @Override
        public void onRefuse(int requestCode, @NonNull String... deniedPermissions) {

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(source, deniedPermissions)) {
                // 第一种：用默认的提示语。
                new SettingDialog(source, deniedPermissions).show();
            }
        }
    };
    // 构造函数
    ProcessRequest(Source source) {
        if (source == null)
            throw new IllegalArgumentException("The target can not be null.");
        this.source = source;
    }
    // 设置申请权限
    @NonNull
    @Override
    public Request permission(String... permissions) {
        this.mPermissions = permissions;
        return this;
    }
    // 设置申请权限
    @NonNull
    @Override
    public Request permission(String[]... permissionsArray) {
        List<String> permissionList = new ArrayList<>();
        for (String[] permissions : permissionsArray) {
            for (String permission : permissions) {
                permissionList.add(permission);
            }
        }
        this.mPermissions = permissionList.toArray(new String[permissionList.size()]);
        return this;
    }
    // 设置再拒绝监听
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public Request setRationaleListener(PermissionActivity.RationaleListener listener) {
        if (listener != null) {
            rationaleListener = listener;
        }
        return this;
    }
    // 设置成功监听
    @NonNull
    @Override
    public Request setOnGrantListener(OnGrantListener grantListener) {
        if (grantListener != null) {
            onGrantListener = grantListener;
        }
        return this;
    }
    // 设计拒绝监听
    @Override
    public Request setOnRefuseListener(OnRefuseListener refuseListener) {
        if (refuseListener != null) {
            onRefuseListener = refuseListener;
        }
        return this;
    }
    // 设置请求码
    private int mRequestCode;
    @Override
    public Request setRequestCode(int requestCode) {
        mRequestCode = requestCode;
        return this;
    }
    // 开始请求
    @Override
    public void start() {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            callbackSucceed();
        } else {
            mDeniedPermissions = getDeniedPermissions(source.getContext(), mPermissions);
            // Denied mPermissions size > 0.
            if (mDeniedPermissions.length > 0) {
                // Remind users of the purpose of mPermissions.
                PermissionActivity.setRationaleListener(rationaleListener);
                Intent intent = new Intent(source.getContext(), PermissionActivity.class);
                intent.putExtra(PermissionActivity.KEY_INPUT_PERMISSIONS, mDeniedPermissions);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                source.startActivity(intent);
            } else { // All permission granted.
                callbackSucceed();
            }
        }
    }

    // 权限 挑选  未获得权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    private static String[] getDeniedPermissions(Context context, @NonNull String... permissions) {
        List<String> deniedList = new ArrayList<>(1);
        for (String permission : permissions)
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
                deniedList.add(permission);
        return deniedList.toArray(new String[deniedList.size()]);
    }
    private void callbackSucceed() {
        if (onGrantListener != null) {
            onGrantListener.onGrant(mRequestCode, mPermissions);
        }
    }

    private void callbackFailed(List<String> deniedList) {
        if (onRefuseListener != null) {
            onRefuseListener.onRefuse(mRequestCode, deniedList.toArray(new String[deniedList.size()]));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void resume() {

        PermissionActivity.setPermissionListener(this);
        Intent intent = new Intent(source.getContext(), PermissionActivity.class);
        intent.putExtra(PermissionActivity.KEY_INPUT_PERMISSIONS, mDeniedPermissions);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        source.startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults) {

        List<String> deniedList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++)
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
                deniedList.add(permissions[i]);

        if (deniedList.isEmpty())
            callbackSucceed();
        else
            callbackFailed(deniedList);
    }
}
